﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MainView.cs" company="SMART business">
//   Copyright (c) 2014 All Rights Reserved
// </copyright>
// <summary>
//   The main view.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using McTools.Xrm.Connection;
using McTools.Xrm.Connection.WinForms;
using UsersSettingsTool.Additional_Classes.Classes;
using UsersSettingsTool.Options;

namespace UsersSettingsTool.Views
{
    /// <summary>
    /// The main view.
    /// </summary>
    public partial class MainView : Form, IMainView
    {
        private const string DisplayMember = "Text";

        private const string ValueMember = "Value";

        private readonly CrmConnectionStatusBar _connectionStatusBar;

        private int _sortColumn = -1;

        private delegate void DelegateMethod<in T>(T value);

        private bool _allUsersChecked;

        private List<Tab> _tabsSource;
        private List<CrmUser> _users;

        public MainView()
        {
            InitializeComponent();

            var connectionManager = new ConnectionManager();
            connectionManager.ConnectionSucceed += ManagerConnectionSucceed;
            connectionManager.ConnectionFailed += ManagerConnectionFailed;
            connectionManager.StepChanged += ManagerStepChanged;

            checkAutoCreateContactOnPromote.CheckStateChanged += AutoCreateContactOnPromoteCheckStateChanged;
            AutoCreateContactOnPromoteCheckStateChanged(null, EventArgs.Empty);

            // Progress bar
            _connectionStatusBar = new CrmConnectionStatusBar(connectionManager, new FormHelper(this, connectionManager));
            var progressBar = new ToolStripProgressBar("progress") { Visible = false, Maximum = 14 };
            _connectionStatusBar.Items.Add(progressBar);
            Controls.Add(_connectionStatusBar);
            //

            btnGetUsers.Click += GetUsersClick;
            lstUsers.ColumnClick += ColumnHeaderClick;
            lstUsers.SelectedIndexChanged += LstUsersSelect;
            lstUsers.ItemChecked += LstUsersChecked;
            lstUsers.ColumnWidthChanging += LstUsersColumnWidthChanging;

            comboPane.SelectedValueChanged += PaneChange;

            userInfo.Click += UserInfoClick;
            UserMailBox.Click += ShowUserMailBoxClick;
            ViewPrivacyStatement.Click += ViewPrivacyStatementClick;

            checkEnableCodePrefixing.CheckedChanged += CheckEnableCodePrefixing;

            cmbEnabled.SelectedIndexChanged += ChangeUserView;

            menuSaveAll.Click += SaveAllClick;

            var location = lblDefaultTab.Location;

            lblDefaultTab.Parent = pictureGeneral;
            lblDefaultTab.Location = new Point(20, 35);
        }

        private void ChangeUserView(object sender, EventArgs e)
        {
            if (_users == null) return;

            var obj = (sender as ToolStripControlHost);
            bool? disabled = true;

            if (obj != null)
                switch (obj.Text)
                {
                    case "All":
                        disabled = null;
                        break;
                    case "Disabled Users":
                        disabled = false;
                        break;
                }

            var list = new List<CrmUser>();
            foreach (var user in _users)
            {
                if (disabled == null)
                {
                    list.Add(user);
                }
                else if (user.IsDisabled != disabled)
                {
                    list.Add(user);
                }
            }

            UpdateUsersList(list);
        }

        private void AutoCreateContactOnPromoteCheckStateChanged(object sender, EventArgs e)
        {
            comboCreateFromEmailOptions.Enabled = checkAutoCreateContactOnPromote.Checked;
        }

        private void LstUsersColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                e.Cancel = true;
                e.NewWidth = lstUsers.Columns[e.ColumnIndex].Width;
            }
        }

        private void CheckAll()
        {
            _allUsersChecked = !_allUsersChecked;

            foreach (dynamic item in lstUsers.Items)
            {
                item.Checked = _allUsersChecked;
            }
        }

        private void SaveAllClick(object sender, EventArgs e)
        {
            if (lstUsers.SelectedItems.Count.Equals(0))
            {
                MessageBox.Show(@"No users are selected for save.", @"Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (SaveChanges != null)
            {
                var checkedUsers = (from ListViewItem user in lstUsers.CheckedItems select user.Tag).ToList();

                SaveChanges(this, new CustomEventArgs(checkedUsers));

                foreach (var item in lstUsers.Items.Cast<ListViewItem>().Where(item => checkedUsers.Contains(item.Tag)))
                {
                    lstUsers.Items[item.Index].Selected = true;
                }
            }
        }

        private void ViewPrivacyStatementClick(object sender, EventArgs e)
        {
            if (ViewYourPrivacyStatement != null)
            {
                ViewYourPrivacyStatement(this, EventArgs.Empty);
            }
        }

        private void LstUsersChecked(object sender, EventArgs e)
        {
            foreach (dynamic item in lstUsers.Items)
            {
                if (item != null)
                {
                    item.Selected = item.Checked;
                }
            }
        }

        private void LstUsersSelect(object sender, EventArgs e)
        {
            foreach (ListViewItem item in lstUsers.Items)
            {
                item.Checked = item.Selected;
            }

            _allUsersChecked = lstUsers.Items.Count.Equals(lstUsers.SelectedItems.Count);

            if (UsersSelect != null)
            {
                var users = (from object item in lstUsers.SelectedItems select ((ListViewItem)item).Tag).ToList();

                if (!users.Count.Equals(0))
                {
                    UsersSelect(this, new CustomEventArgs(users));
                }
            }
        }

        private void CheckEnableCodePrefixing(object sender, EventArgs e)
        {
            txtCountryRegionPrefix.Enabled = checkEnableCodePrefixing.Checked;
        }

        private void UserInfoClick(object sender, EventArgs e)
        {
            if (ShowUserInfo != null)
            {
                ShowUserInfo(this, EventArgs.Empty);
            }
        }

        private void ShowUserMailBoxClick(object sender, EventArgs e)
        {
            if (ShowUserMailBox != null)
            {
                ShowUserMailBox(this, EventArgs.Empty);
            }
        }

        private void ColumnHeaderClick(object obj, ColumnClickEventArgs e)
        {
            lstUsers.SelectedIndexChanged -= LstUsersSelect;
            lstUsers.ItemChecked -= LstUsersChecked;

            if (!lstUsers.Items.Count.Equals(0))
            {
                if (e.Column == 0)
                {
                    CheckAll();
                    lstUsers.Columns[e.Column].Text = _allUsersChecked ? "☑" : "☒";

                    if (UsersSelect != null)
                    {
                        var users = (from ListViewItem user in lstUsers.CheckedItems select user.Tag).ToList();

                        if (!users.Count.Equals(0))
                        {
                            UsersSelect(this, new CustomEventArgs(users));
                        }
                    }
                }
                else
                {
                    var list = obj as ListView;

                    if (list == null)
                    {
                        return;
                    }

                    if (e.Column != _sortColumn)
                    {
                        _sortColumn = e.Column;
                        list.Sorting = SortOrder.Ascending;
                    }
                    else
                    {
                        list.Sorting = list.Sorting == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending;
                    }

                    list.Sort();

                    list.ListViewItemSorter = new ColumnSorter(e.Column, list.Sorting);
                }
            }

            lstUsers.SelectedIndexChanged += LstUsersSelect;
            lstUsers.ItemChecked += LstUsersChecked;
        }

        private void GetUsersClick(object sender, EventArgs e)
        {
            if (GetUsers != null)
            {
                GetUsers(null, EventArgs.Empty);
                UnderineDisabled();
            }
        }

        private void UnderineDisabled()
        {
            foreach (ListViewItem user in lstUsers.Items)
            {
                if (user.SubItems[7].Text == @"True")
                {
                    user.BackColor = Color.Linen;
                }
            }
        }

        private void UpdateUsersList(List<CrmUser> users)
        {
            if (lstUsers.InvokeRequired)
            {
                var callback = new DelegateMethod<List<CrmUser>>(SetUserList);
                Invoke(callback, users);
            }
            else
            {
                lstUsers.BeginUpdate();

                lstUsers.Items.Clear();

                if (_users == null) return;

                var enabled = cmbEnabled.Text;

                foreach (var user in users)
                {
                    var listViewItem = new ListViewItem { Tag = user.Id };
                    listViewItem.SubItems.Add(user.FullName);
                    listViewItem.SubItems.Add(user.BusinessUnit);
                    listViewItem.SubItems.Add(user.Pane.Value);
                    listViewItem.SubItems.Add(user.Tab.Text);
                    listViewItem.SubItems.Add(user.RecordsPerPage.Text);
                    listViewItem.SubItems.Add(user.TimeZone.Text);
                    listViewItem.SubItems.Add(user.IsDisabled.ToString());

                    switch (enabled)
                    {
                        case "All":
                        case "":
                            lstUsers.Items.AddRange(new[] { listViewItem });
                            break;
                        case "Enabled Users":
                            if (!user.IsDisabled)
                                lstUsers.Items.AddRange(new[] { listViewItem });
                            break;
                        case "Disabled Users":
                            if (user.IsDisabled)
                                lstUsers.Items.AddRange(new[] { listViewItem });
                            break;
                    }
                }

                UnderineDisabled();

                cmbEnabled.Visible = !lstUsers.Items.Count.Equals(0);

                lstUsers.EndUpdate();
            }
        }

        public void SetUserList(List<CrmUser> users)
        {
            _users = users;
            UpdateUsersList(users);
        }

        #region General Tab

        private void PaneChange(object sender, EventArgs e)
        {
            if (comboPane.SelectedItem != null && _tabsSource != null)
            {
                comboTabs.BeginUpdate();

                dynamic pane = comboPane.SelectedItem;

                comboTabs.Enabled = pane.Value != string.Empty;

                comboTabs.DisplayMember = DisplayMember;
                comboTabs.ValueMember = ValueMember;

                var source = (from tab in _tabsSource where tab.Id.Equals(pane.Value) select new Tab(tab.Text, tab.Value)).ToList();

                comboTabs.Items.Clear();

                comboTabs.SelectedIndex = -1;
                comboTabs.SelectedItem = null;
                comboTabs.Text = null;

                foreach (var tab in source)
                {
                    comboTabs.Items.Add(new Pane { Text = tab.Text, Value = tab.Value });
                }

                comboTabs.EndUpdate();
            }
        }

        public void FillTimeZones(List<TimeZones> zones)
        {
            if (comboTimeZone.InvokeRequired)
            {
                var callback = new DelegateMethod<List<TimeZones>>(FillTimeZones);
                Invoke(callback, zones);
            }
            else
            {
                comboTimeZone.BeginUpdate();

                comboTimeZone.DisplayMember = DisplayMember;
                comboTimeZone.ValueMember = ValueMember;

                comboTimeZone.DataSource = zones;

                comboTimeZone.EndUpdate();
            }
        }

        public void FillPanes(List<Pane> panes)
        {
            if (comboPane.InvokeRequired)
            {
                var callback = new DelegateMethod<List<Pane>>(FillPanes);
                Invoke(callback, panes);
            }
            else
            {
                comboPane.BeginUpdate();

                comboPane.DisplayMember = DisplayMember;
                comboPane.ValueMember = ValueMember;

                // comboPane.DataSource = panes;

                foreach (var pane in panes)
                {
                    comboPane.Items.Add(new Pane { Text = pane.Text, Value = pane.Value });
                }

                comboPane.EndUpdate();
            }
        }

        public void FillTabs(List<Tab> tabs)
        {
            if (comboTabs.InvokeRequired)
            {
                var callback = new DelegateMethod<List<Tab>>(FillTabs);
                Invoke(callback, tabs);
            }
            else
            {
                comboTabs.BeginUpdate();

                _tabsSource = tabs;
                var pane = (Pane)comboPane.SelectedItem;

                comboTabs.DisplayMember = DisplayMember;
                comboTabs.ValueMember = ValueMember;

                var source = new List<Tab>();
                if (pane != null)
                {

                    source = (from tab in _tabsSource
                              where tab.Id.Equals(pane.Value)
                              select new Tab(tab.Text, tab.Value)).ToList();
                }

                comboTabs.SelectedIndex = -1;
                comboTabs.SelectedItem = null;
                comboTabs.Text = null;

                foreach (var tab in source)
                {
                    comboTabs.Items.Add(new Tab { Text = tab.Text, Value = tab.Value });
                }

                comboTabs.EndUpdate();
            }
        }

        public void FillCurrencies(List<Currency> currencies)
        {
            if (comboCurrency.InvokeRequired)
            {
                var callback = new DelegateMethod<List<Currency>>(FillCurrencies);
                Invoke(callback, currencies);
            }
            else
            {
                comboCurrency.BeginUpdate();

                comboCurrency.DisplayMember = DisplayMember;
                comboCurrency.ValueMember = ValueMember;

                comboCurrency.DataSource = currencies;

                comboCurrency.EndUpdate();
            }
        }

        public void SetTab(object tab)
        {
            if (comboTabs.InvokeRequired)
            {
                var callback = new DelegateMethod<List<object>>(SetTab);
                Invoke(callback, tab);
            }
            else
            {
                comboTabs.BeginUpdate();

                comboTabs.DisplayMember = DisplayMember;
                comboTabs.ValueMember = ValueMember;

                comboTabs.Enabled = !comboTabs.Items.Count.Equals(0);

                if (comboTabs.Items.Count.Equals(0))
                {
                    comboTabs.Items.Clear();
                    comboTabs.SelectedIndex = -1;
                    comboTabs.SelectedItem = null;
                    comboTabs.Text = null;
                }
                else
                {
                    comboTabs.SelectedIndex = comboTabs.FindStringExact((string)tab);
                }

                comboTabs.EndUpdate();
            }
        }

        public void SetPane(object pane)
        {
            if (comboPane.InvokeRequired)
            {
                var callback = new DelegateMethod<List<object>>(SetPane);
                Invoke(callback, pane);
            }
            else
            {
                comboPane.BeginUpdate();

                comboPane.DisplayMember = DisplayMember;
                comboPane.ValueMember = ValueMember;

                comboPane.SelectedIndex = comboPane.FindStringExact((string)pane);

                comboPane.EndUpdate();
            }
        }

        public void SetRecordPerPage(object recordsCount)
        {
            if (comboRecordsPerPage.InvokeRequired)
            {
                var callback = new DelegateMethod<List<object>>(SetRecordPerPage);
                Invoke(callback, recordsCount);
            }
            else
            {
                comboRecordsPerPage.BeginUpdate();

                comboRecordsPerPage.SelectedIndex = comboRecordsPerPage.FindStringExact((string)recordsCount);

                comboRecordsPerPage.EndUpdate();
            }
        }

        public void SetTimeZone(object timeZoneCode)
        {
            if (comboTimeZone.InvokeRequired)
            {
                var callback = new DelegateMethod<List<object>>(SetTimeZone);
                Invoke(callback, timeZoneCode);
            }
            else
            {
                comboTimeZone.BeginUpdate();

                comboTimeZone.SelectedIndex = comboTimeZone.FindStringExact((string)timeZoneCode);

                comboTimeZone.EndUpdate();
            }
        }

        public void SetAdvancedFindMode(string mode)
        {
            if (radioFindModeSimple.InvokeRequired || radioFindModeDetailed.InvokeRequired)
            {
                var callback = new DelegateMethod<string>(SetAdvancedFindMode);
                Invoke(callback, mode);
            }
            else
            {
                if (mode.Equals("1"))
                {
                    radioFindModeSimple.Checked = true;
                    return;
                }

                radioFindModeDetailed.Checked = true;
            }
        }

        public void SetCurrency(string currency)
        {
            if (comboCurrency.InvokeRequired)
            {
                var callback = new DelegateMethod<string>(SetCurrency);
                Invoke(callback, currency);
            }
            else
            {
                comboCurrency.BeginUpdate();

                comboCurrency.SelectedIndex = comboCurrency.FindStringExact(currency);

                comboCurrency.EndUpdate();
            }
        }

        public void SetHighContrast(bool isHighContrast)
        {
            if (checkHighContrast.InvokeRequired)
            {
                var callback = new DelegateMethod<bool>(SetHighContrast);
                Invoke(callback, isHighContrast);
            }
            else
            {
                checkHighContrast.Checked = isHighContrast;
            }
        }

        public void SetCountryRegionCodePrefixing(bool isCountryRegionCodePrefixing)
        {
            if (checkEnableCodePrefixing.InvokeRequired)
            {
                var callback = new DelegateMethod<bool>(SetCountryRegionCodePrefixing);
                Invoke(callback, isCountryRegionCodePrefixing);
            }
            else
            {
                checkEnableCodePrefixing.Checked = isCountryRegionCodePrefixing;
            }
        }

        public void SetCountryCode(string countryCode)
        {
            if (txtCountryRegionPrefix.InvokeRequired)
            {
                var callback = new DelegateMethod<string>(SetCountryCode);
                Invoke(callback, countryCode);
            }
            else
            {
                txtCountryRegionPrefix.Text = countryCode;
            }
        }

        public void FillRecordsPerPage(List<RecordPerPage> recordsCount)
        {
            if (comboRecordsPerPage.InvokeRequired)
            {
                var callback = new DelegateMethod<List<RecordPerPage>>(FillRecordsPerPage);
                Invoke(callback, recordsCount);
            }
            else
            {
                comboRecordsPerPage.BeginUpdate();

                comboRecordsPerPage.DisplayMember = DisplayMember;
                comboRecordsPerPage.ValueMember = ValueMember;

                // comboRecordsPerPage.DataSource = recordsCount;

                comboRecordsPerPage.Items.Clear();

                foreach (var perPage in recordsCount)
                {
                    comboRecordsPerPage.Items.Add(new Pane { Text = perPage.Text, Value = perPage.Value.ToString() });
                }

                comboRecordsPerPage.EndUpdate();
            }
        }

        #endregion General Tab

        #region Formats

        //public void SetFormats(List<Format> formats)
        //{
        //    if (comboFormats.InvokeRequired)
        //    {
        //        var callback = new DelegateMethod<List<Format>>(SetFormats);
        //        Invoke(callback, formats);
        //    }
        //    else
        //    {
        //        comboFormats.BeginUpdate();

        //        comboFormats.DisplayMember = DisplayMember;
        //        comboFormats.ValueMember = ValueMember;

        //        comboFormats.DataSource = formats;

        //        comboFormats.EndUpdate();
        //    }
        //}

        #endregion Formats

        #region Activities

        public void FillCalendar(List<CalendarList> calendar)
        {
            if (comboCalendar.InvokeRequired)
            {
                var callback = new DelegateMethod<List<CalendarList>>(FillCalendar);
                Invoke(callback, calendar);
            }
            else
            {
                comboCalendar.BeginUpdate();

                comboCalendar.DisplayMember = DisplayMember;
                comboCalendar.ValueMember = ValueMember;

                comboCalendar.DataSource = calendar;

                comboCalendar.EndUpdate();
            }
        }

        public void FillTimes(List<object> times)
        {
            SetStartTimes(new List<object>(times));
            SetEndTimes(new List<object>(times));
        }

        public void SetCalendarView(string calendarView)
        {
            if (comboCalendar.InvokeRequired)
            {
                var callback = new DelegateMethod<string>(SetCalendarView);
                Invoke(callback, calendarView);
            }
            else
            {
                comboCalendar.BeginUpdate();

                comboCalendar.SelectedIndex = comboCalendar.FindStringExact(calendarView);

                comboCalendar.EndUpdate();
            }
        }

        public void SetWorkDayStartTime(string workDayStartTime)
        {
            if (comboStartTime.InvokeRequired)
            {
                var callback = new DelegateMethod<string>(SetWorkDayStartTime);
                Invoke(callback, workDayStartTime);
            }
            else
            {
                comboStartTime.BeginUpdate();

                comboStartTime.SelectedIndex = comboStartTime.FindStringExact(workDayStartTime);

                comboStartTime.EndUpdate();
            }
        }

        public void SetWorkDayStopTime(string workDayStopTime)
        {
            if (comboEndTime.InvokeRequired)
            {
                var callback = new DelegateMethod<string>(SetWorkDayStopTime);
                Invoke(callback, workDayStopTime);
            }
            else
            {
                comboEndTime.BeginUpdate();

                comboEndTime.SelectedIndex = comboEndTime.FindStringExact(workDayStopTime);

                comboEndTime.EndUpdate();
            }
        }

        private void SetEndTimes(List<object> times)
        {
            if (comboEndTime.InvokeRequired)
            {
                var callback = new DelegateMethod<List<object>>(SetEndTimes);
                Invoke(callback, times);
            }
            else
            {
                comboEndTime.BeginUpdate();

                comboEndTime.DisplayMember = DisplayMember;
                comboEndTime.ValueMember = ValueMember;

                comboEndTime.DataSource = times;

                comboEndTime.EndUpdate();
            }
        }

        private void SetStartTimes(List<object> times)
        {
            if (comboStartTime.InvokeRequired)
            {
                var callback = new DelegateMethod<List<object>>(SetStartTimes);
                Invoke(callback, times);
            }
            else
            {
                comboStartTime.BeginUpdate();

                comboStartTime.DisplayMember = DisplayMember;
                comboStartTime.ValueMember = ValueMember;

                comboStartTime.DataSource = times;

                comboStartTime.EndUpdate();
            }
        }

        #endregion Activities

        #region Email

        public void SetTrackValues(string filteringMethod)
        {
            if (comboTrackValues.InvokeRequired)
            {
                var callback = new DelegateMethod<string>(SetTrackValues);
                Invoke(callback, filteringMethod);
            }
            else
            {
                comboTrackValues.BeginUpdate();

                comboTrackValues.SelectedIndex = comboTrackValues.FindStringExact(filteringMethod);

                comboTrackValues.EndUpdate();
            }
        }

        public void SetAutoCreateEntity(string autoCreateOption)
        {
            if (comboCreateFromEmailOptions.InvokeRequired)
            {
                var callback = new DelegateMethod<string>(SetAutoCreateEntity);
                Invoke(callback, autoCreateOption);
            }
            else
            {
                comboCreateFromEmailOptions.SelectedIndex = comboCreateFromEmailOptions.FindStringExact(autoCreateOption);
            }
        }

        public void SetAutoCreateOption(bool isAutoCreate)
        {
            if (checkAutoCreateContactOnPromote.InvokeRequired)
            {
                var callback = new DelegateMethod<bool>(SetAutoCreateOption);
                Invoke(callback, isAutoCreate);
            }
            else
            {
                checkAutoCreateContactOnPromote.Checked = isAutoCreate;
            }
        }

        public void SetSendAsAllowed(bool isSendAsAllowed)
        {
            if (checkSendAsAllowed.InvokeRequired)
            {
                var callback = new DelegateMethod<bool>(SetSendAsAllowed);
                Invoke(callback, isSendAsAllowed);
            }
            else
            {
                checkSendAsAllowed.Checked = isSendAsAllowed;
            }
        }

        public void SetTrackValues(List<object> trackValues)
        {
            if (comboTrackValues.InvokeRequired)
            {
                var callback = new DelegateMethod<List<object>>(SetTrackValues);
                Invoke(callback, trackValues);
            }
            else
            {
                comboTrackValues.BeginUpdate();

                comboTrackValues.DisplayMember = DisplayMember;
                comboTrackValues.ValueMember = ValueMember;

                comboTrackValues.DataSource = trackValues;

                comboTrackValues.EndUpdate();
            }
        }

        public void SetCreateFromEmailOptions(List<object> createFromEmailOptions)
        {
            if (comboCreateFromEmailOptions.InvokeRequired)
            {
                var callback = new DelegateMethod<List<object>>(SetCreateFromEmailOptions);
                Invoke(callback, createFromEmailOptions);
            }
            else
            {
                comboCreateFromEmailOptions.BeginUpdate();

                comboCreateFromEmailOptions.DisplayMember = DisplayMember;
                comboCreateFromEmailOptions.ValueMember = ValueMember;

                comboCreateFromEmailOptions.DataSource = createFromEmailOptions;

                comboCreateFromEmailOptions.EndUpdate();
            }
        }

        #endregion Email

        #region Privacy

        public void SetReportScriptErrors(int reportScriptErrors)
        {
            if (checkAutoCreateContactOnPromote.InvokeRequired)
            {
                var callback = new DelegateMethod<int>(SetReportScriptErrors);
                Invoke(callback, reportScriptErrors);
            }
            else
            {
                switch (reportScriptErrors)
                {
                    case 1:
                        radioAskMeForPermission.Checked = true;
                        break;
                    case 2:
                        radioAutomaticallySendanErrorReport.Checked = true;
                        break;
                    case 3:
                        radioNeverSendAnErrorReport.Checked = true;
                        break;
                    default:
                        radioAskMeForPermission.Checked = true;
                        break;
                }
            }
        }

        #endregion

        #region Languages

        public void FillLanguages(List<object> languages)
        {
            SetUiLanguage(new List<object>(languages));
            SetHelpLanguage(new List<object>(languages));
        }

        public void FillBaseLanguage(string language)
        {
            if (txtBaseLanguage.InvokeRequired)
            {
                var callback = new DelegateMethod<string>(FillBaseLanguage);
                Invoke(callback, language);
            }
            else
            {
                txtBaseLanguage.Text = language;
            }
        }

        public void SetHelpLanguage(string languageCode)
        {
            if (comboHelpLanguage.InvokeRequired)
            {
                var callback = new DelegateMethod<string>(SetHelpLanguage);
                Invoke(callback, languageCode);
            }
            else
            {
                comboHelpLanguage.SelectedIndex = comboHelpLanguage.FindStringExact(languageCode);
            }
        }

        public void SetUiLanguage(string uiLanguageCode)
        {
            if (comboUiLanguage.InvokeRequired)
            {
                var callback = new DelegateMethod<string>(SetUiLanguage);
                Invoke(callback, uiLanguageCode);
            }
            else
            {
                comboUiLanguage.SelectedIndex = comboHelpLanguage.FindStringExact(uiLanguageCode);
            }
        }

        private void SetHelpLanguage(object languages)
        {
            if (comboHelpLanguage.InvokeRequired)
            {
                var callback = new DelegateMethod<List<object>>(SetHelpLanguage);
                Invoke(callback, languages);
            }
            else
            {
                comboHelpLanguage.BeginUpdate();

                comboHelpLanguage.DisplayMember = DisplayMember;
                comboHelpLanguage.ValueMember = ValueMember;

                comboHelpLanguage.DataSource = languages;

                comboHelpLanguage.EndUpdate();
            }
        }

        private void SetUiLanguage(object languages)
        {
            if (comboUiLanguage.InvokeRequired)
            {
                var callback = new DelegateMethod<List<object>>(SetUiLanguage);
                Invoke(callback, languages);
            }
            else
            {
                comboUiLanguage.BeginUpdate();

                comboUiLanguage.DisplayMember = DisplayMember;
                comboUiLanguage.ValueMember = ValueMember;

                comboUiLanguage.DataSource = languages;

                comboUiLanguage.EndUpdate();
            }
        }

        #endregion Languages

        #region Connection

        private void ManagerStepChanged(object sender, StepChangedEventArgs e)
        {
            if (ConnectionManagerStepChanged != null)
            {
                ConnectionManagerStepChanged(this, e);
            }
        }

        private void ManagerConnectionFailed(object sender, ConnectionFailedEventArgs e)
        {
            if (ConnectionManagerConnectionFailed != null)
            {
                ConnectionManagerConnectionFailed(this, e);
            }
        }

        private void ManagerConnectionSucceed(object sender, ConnectionSucceedEventArgs e)
        {
            if (ConnectionManagerConnectionSucceed != null)
            {
                try
                {
                    ConnectionManagerConnectionSucceed(this, e);

                    _connectionStatusBar.SetConnectionStatus(true, e.ConnectionDetail);
                    _connectionStatusBar.SetMessage(string.Empty);
                }
                catch (Exception ex)
                {
                    ManagerConnectionFailed(sender, new ConnectionFailedEventArgs { FailureReason = ex.Message });
                }
            }
        }

        public void SetConnectionStatus(string message)
        {
            if (_connectionStatusBar != null)
            {
                _connectionStatusBar.SetMessage(message);
            }
        }

        #endregion

        #region IMainView

        public event EventHandler ShowUserInfo;

        public event EventHandler ViewYourPrivacyStatement;

        public event EventHandler ShowUserMailBox;

        public event EventHandler UsersSelect;

        // public event EventHandler GetTabs;
        public event EventHandler ConnectionManagerStepChanged;

        public event EventHandler GetUsers;

        public event EventHandler ConnectionManagerConnectionFailed;

        public event EventHandler ConnectionManagerConnectionSucceed;

        public event EventHandler SaveChanges;

        #endregion IMainView

        // public string GetAutoCreateOption()
        // {
        //    return checkAutoCreateContactOnPromote.Checked.ToString();
        // }
        public int GetRecordsPerPage()
        {
            dynamic value = comboRecordsPerPage.SelectedItem;
            if (value != null)
                return Convert.ToInt32(value.Value);

            return -1;
        }

        public Guid GetCurrency()
        {
            dynamic value = comboCurrency.SelectedItem;
            return value.Value == Guid.Empty ? Guid.Empty : (Guid)value.Value;
        }

        public string GetPane()
        {
            dynamic value = comboPane.SelectedItem;
            return value != null ? value.Value : string.Empty;
        }

        public string GetTab()
        {
            dynamic value = comboTabs.SelectedItem;
            return value != null ? value.Value : string.Empty;
        }

        public int GetAdvFindMode()
        {
            return radioFindModeSimple.Checked ? 1 : 2;
        }

        public int GetTimeZone()
        {
            dynamic value = comboTimeZone.SelectedItem;
            return value != null ? Convert.ToInt32(value.Value) : -1;
        }

        public bool GetIsEnabledHighContrast()
        {
            return checkHighContrast.Checked;
        }

        public bool GetEnableCountryRegionCodePrefixing()
        {
            return checkEnableCodePrefixing.Checked;
        }

        public string GetCountryCode()
        {
            return txtCountryRegionPrefix.Text;
        }

        public int GetCalendarView()
        {
            dynamic value = comboCalendar.SelectedItem;
            return value != null ? value.Value : -1;
        }

        public string GetWorkDayStartTime()
        {
            dynamic value = comboStartTime.SelectedItem;
            return value != null ? value.Value : string.Empty;
        }

        public string GetWorkDayStopTime()
        {
            dynamic value = comboEndTime.SelectedItem;
            return value != null ? value.Value : string.Empty;
        }

        public bool GetIsSendAsAllowed()
        {
            return checkSendAsAllowed.Checked;
        }

        // public int? GetReportScriptErrors()
        // {
        //    dynamic value = comboTrackValues.SelectedItem;
        //    return Convert.ToInt32(value.Value);
        // }
        public int GetIsAutoCreateContactOnPromote()
        {
            if (!checkAutoCreateContactOnPromote.Checked)
            {
                return 0;
            }

            dynamic value = comboCreateFromEmailOptions.SelectedItem;
            return value != null ? value.Value : -1;
        }

        public int GetIncomingEmailFilteringMethod()
        {
            dynamic value = comboTrackValues.SelectedItem;
            return value != null ? value.Value : -1;
        }

        public int GetSetReportScriptErrors()
        {
            if (radioAskMeForPermission.Checked)
            {
                return 1;
            }

            if (radioAutomaticallySendanErrorReport.Checked)
            {
                return 2;
            }

            if (radioNeverSendAnErrorReport.Checked)
            {
                return 3;
            }

            return 0;
        }

        public int GetHelpLanguage()
        {
            dynamic value = comboHelpLanguage.SelectedItem;
            if (value != null && value.Value.ToString() != string.Empty)
            {
                return Convert.ToInt32(value.Value);
            }

            return 1033;
        }

        public int GetUiLanguage()
        {
            dynamic value = comboUiLanguage.SelectedItem;
            if (value != null && value.Value.ToString() != string.Empty)
            {
                return Convert.ToInt32(value.Value);
            }

            return 1033;
        }

        public void SetProgress(int i)
        {

            if (_connectionStatusBar.InvokeRequired)
            {
                var callback = new DelegateMethod<int>(SetProgress);
                Invoke(callback, i);
            }
            else
            {

                var progressBar = _connectionStatusBar.Items["progress"] as ToolStripProgressBar;

                if (progressBar != null && progressBar.ProgressBar != null)
                {
                    progressBar.Visible = true;

                    progressBar.ProgressBar.Value = i;


                    if (i.Equals(progressBar.Maximum))
                    {
                        progressBar.Visible = false;
                    }
                }
            }
        }
    }
}
